//
//  ZCPhotoManager.m
//  BaiSi
//
//  Created by 张灿 on 16/5/7.
//  Copyright © 2016年 张灿. All rights reserved.
//

#import "ZCPhotoManager.h"
#import <Photos/Photos.h>

@implementation ZCPhotoManager

// 获取已有相册
+ (PHAssetCollection *)getAssetCollection:(NSString *)title
{
    // 获取到相册结构集
    PHFetchResult *results = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (PHAssetCollection *assetCollection in results) {
        
        if ([assetCollection.localizedTitle isEqualToString:title]) {
            return assetCollection;
        }
    }
    
    return nil;
}

+ (void)addImage:(UIImage *)image toAlbum:(NSString *)title completionHandler:(void(^)(BOOL success, NSError *error))completionHandler
{
    // 获取相簿
    PHPhotoLibrary *lib = [PHPhotoLibrary sharedPhotoLibrary];
    
    [lib performChanges:^{
        // 只有在这个Block中才能对相册进行操作
        // 先判断是否已有自定义相册，如果有自定义相册，直接把图片添加到已有相册
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
        
        // 获取相册
        PHAssetCollection *assetCollection = [self getAssetCollection:title];
        
        if (assetCollection) {
            // 有自定义相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        } else {
            // 创建自定义相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        }
        
        // 2.创建图片请求对象
        PHAssetChangeRequest *assetRequset = [PHAssetCreationRequest creationRequestForAssetFromImage:image];
        
        // 3.把图片放在自定义相册 PHAsset:照片
        [assetCollectionChangeRequest addAssets:@[assetRequset.placeholderForCreatedAsset]];
        
    } completionHandler:completionHandler];
    
}


@end
